package com.hubu.web;

import com.hubu.mapper.administratorUserMapper;
import com.hubu.pojo.student_Information;
import com.hubu.pojo.teacher_Information;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/insertStudent")
public class insertStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer = response.getWriter();
        //获取学生数据
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        String age=request.getParameter("age");
        String class_id=request.getParameter("class_id");

        //封装学生数据
        student_Information student=new student_Information();
        student.setId(id);
        student.setName(name);
        student.setGender(sex);
        student.setAge(Integer.parseInt(age));
        student.setClass_id(class_id);



        //2. 调用Mybatis完成查询
        // 2.1 获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);

        //2.2获取SqlSession对象
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //2.3 获取Mapper
        administratorUserMapper userMapper=sqlSession.getMapper(administratorUserMapper.class);

        userMapper.insertStudent(student);
        //提交数据库
        sqlSession.commit();
        //释放资源

        writer.println("<script type='text/javascript'>");
        writer.println("alert('录入成功！');");
        writer.println("window.location='" + request.getContextPath() + "/insertStudent.jsp';");
        writer.println("</script>");
        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}